package com.atgugu.flink.chapter08;

import com.atgugu.flink.bean.OrderEvent;
import com.atgugu.flink.util.AtguiguUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.EventTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.List;

/**
 * @Author lzc
 * @Date 2022/4/8 9:00
 * private Long orderId;
 * private String eventType;
 * private String txId;
 * private Long eventTime;
 */
public class Flink06_Project_High_Order {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
    
        env
            .readTextFile("input/OrderLog.csv")
            .map(log -> {
                String[] data = log.split(",");
                return new OrderEvent(
                    Long.valueOf(data[0]),
                    data[1],
                    data[2],
                    Long.parseLong(data[3]) * 1000
                );
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<OrderEvent>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((order, ts) -> order.getEventTime())
            )
            .keyBy(OrderEvent::getOrderId)
            .window(EventTimeSessionWindows.withGap(Time.minutes(45)))
            .process(new ProcessWindowFunction<OrderEvent, String, Long, TimeWindow>() {
    
                private ValueState<OrderEvent> createState;
    
                @Override
                public void open(Configuration parameters) throws Exception {
                    createState = getRuntimeContext().getState(new ValueStateDescriptor<OrderEvent>("createState", OrderEvent.class));
                }
    
                @Override
                public void process(Long key,
                                    Context ctx,
                                    Iterable<OrderEvent> elements, // 最多两个
                                    Collector<String> out) throws Exception {
                    List<OrderEvent> list = AtguiguUtil.toList(elements);
                    int size = list.size();
                    if (size == 2) {
                        out.collect("订单: " + key + " 正常支付....");
                    }else{
                        // 如果是create : 这个订单可能没有pay ,有可能pay与create超过45分钟
                        
                        // 如果是pay: 这个订单可能是没有create, 还有可能pay超过create 45分钟
                        
                        // 如果是create, 先把create放入到状态, 等pay来了, 看状态有没有create...
                        OrderEvent orderEvent = list.get(0);
                        if ("create".equals(orderEvent.getEventType())) {
                            createState.update(orderEvent);
                            
                        }else{
                            // 支付来了
                            if (createState.value() == null) {
                                // 没有create, 但是有pay
                                out.collect("订单: " + key + " 异常: 没有下单,但是有人支付钱....");
                            }else{
                                // create存在, pay来了, 但是没有在一个窗口, 证明超时支付
                                out.collect("订单: " + key + " 异常: 超时方支付....");
                            }
                        }
                    }
                }
            })
            .print();
        
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
